#!/bin/bash

set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

#下载依赖和工具包
function install_development() {
  sudo yum install -y wget tar libatomic environment-modules
  source /etc/profile
}

#获取毕昇编译器
function download_bisheng() {
  echo "# 毕昇编译器正在下载"
  wget -t 40 -c -P "$1" \
    https://mirrors.huaweicloud.com/kunpeng/archive/compiler/bisheng_compiler/bisheng-compiler-2.1.0-aarch64-linux.tar.gz
  
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# 毕昇编译器已经下载成功\033[0m"
  else
    echo -e "\033[31m# 毕昇编译器下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_bisheng() {
  echo "# 毕昇编译器正在安装"
  tar -xzf "$1"/bisheng-compiler-2.1.0-aarch64-linux.tar.gz -C "$1" && rm -rf "$1"/bisheng-compiler-2.1.0-aarch64-linux.tar.gz
  mkdir -p "$2"/bisheng-compiler-2.1.0 && cp -r "$1"/bisheng-compiler-2.1.0-aarch64-linux/* "$2"/bisheng-compiler-2.1.0/
  echo -e "\033[1;32;1m# 毕昇编译器已经安装完毕\033[0m"
}

function write_bisheng_module() {
  cat >"$1/bisheng-compiler-2.1.0/bisheng_modulefiles" <<EOF
#%Module1.0
conflict bisheng
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set BISHENG \$pwd
setenv BISHENG \$BISHENG
prepend-path PATH \$BISHENG/bin
prepend-path LD_LIBRARY_PATH \$BISHENG/lib
EOF
}

function main() {
    set -e
    is_check_build_install_directory "$1" "$2" "bisheng-compiler-2.1.0.sh"
    is_equal_build_install_path "$1" "$2"
    install_development
    download_bisheng "$1"
    install_bisheng "$1" "$2"
    write_bisheng_module "$2"
    rm -rf "$1"/bisheng-compiler-2.1.0-aarch64-linux
}

main "$@"